package org.finesys.common.netty.websocket.handler;

import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * 服务器超时处理类：可以处理读超时、写超时和读写超时。<br/>
 * 读超时：客户端在规定时间内未上发心跳或业务数据，则被触发<br/>
 * 写超时：服务端在规定时间内未下行业务数据或未下行response信息，则被触发
 */
public class CommonChannelIdleTimeoutHandler extends ChannelDuplexHandler {

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

        if (evt instanceof IdleStateEvent) {
            IdleState idleState = ((IdleStateEvent) evt).state();
            if (idleState == IdleState.READER_IDLE) {
                //关闭读空闲的连接
                ctx.close();
            } else if (idleState == IdleState.WRITER_IDLE) {
                //关闭写空闲的连接
                ctx.close();
            }
            return;
        }


        super.userEventTriggered(ctx, evt);
    }
}
